<template>
  <div class="ek-upload-file">
    <el-upload
      ref="ekUpload"
      v-model:file-list="value"
      class="ek-upload-file-box"
      :action="action"
      :multiple="multiple"
      :disabled="disabled"
      :accept="accept"
      :limit="limit"
      :auto-upload="autoUpload"
      :before-upload="handleBeforeUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="handleBeforeRemove"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :on-change="handleChange"
      :headers="headers"
    >
      <el-button type="primary" class="ek-upload-file-btn" >选择文件</el-button>
      <!-- <template #tip>
        <div class="el-upload__tip">
          jpg/png files with a size less than 500KB.
        </div>
      </template> -->
      <!-- <template #file>
      
      </template> -->
    </el-upload>
  </div>
</template>

<script setup>
import { formatFileSize } from "@/utils/common";
import { defineProps, defineEmits, computed, ref, getCurrentInstance, watch, defineExpose } from "vue";

const props = defineProps({
  // 值
  modelValue: {
    type: String,
    default: '',
  },
  // 禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 上传地址
  action: {
    type: String,
    default: "http://temp.demo.top/admin/upload/upload",
  },
  // 多文件上传
  multiple: {
    type: Boolean,
    default: false,
  },
  // 上传文件类型
  accept: {
    type: String,
    default: "*",
  },
  // 上传文件数量限制
  limit: {
    type: Number,
    default: 0,
  },
   // 上传文件大小限制,0不限制
  size: {
    type:Number,
    default: 0,
  },
  // 自动上传
  autoUpload: {
    type: Boolean,
    default: true,
  },
  // 请求头
  headers: {
    type: Object,
    default: {},
  }
});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();

const { $storage, $ekMessage } = globalProperties;

const emit = defineEmits([
  "update:modelValue",
  "on-preview",
  "on-success",
  "on-error"
]);

let fileList = ref([]);
let value = props.modelValue ? JSON.parse(props.modelValue): [];
fileList.value = props.modelValue ?  JSON.parse(props.modelValue) : [];

watch(
  () => props.modelValue,
  (newVal) => {
    value = newVal ? JSON.parse(newVal): [];
    fileList.value = newVal ?  JSON.parse(newVal) : [];
  }
);

function getFileList(files) {

  let list = [];
  files.forEach(item => {
    delete item.uid
    delete item.status
    if(item.response){
      list.push(item.response.data);
    }else {
      list.push(item);
    }
  });
  return list;
}
// 上传之前
function handleBeforeUpload(rawFile) {
  // 进行文件类型校验
  if(props.accept != "*"){
    let accept = props.accept.split(",")
    let fileType = rawFile.type
    if(!accept.includes(fileType)){
      $ekMessage.error(`文件类型不正确，请上传${props.accept}类型的文件`)
      return false
    }
  }
  // 进行文件大小校验
  if(props.size !=  0){
    if(rawFile.size > props.size ){
      $ekMessage.error(`文件大小不能超过${formatFileSize(props.size)}`)
      return false
    }
  }
}
// 点击文件列表中已经上传的文件
function handlePreview(uploadFile) {
  emit('on-preview',uploadFile)
}
function handleBeforeRemove(uploadFile, uploadFiles) {

}
// 移除文件列表中已经上传的文件
function handleRemove(uploadFile, uploadFiles) {
  let newfileList = [];
  if (uploadFiles.length) {
    newfileList = getFileList(JSON.parse(JSON.stringify(uploadFiles)));
    fileList.value = JSON.parse(JSON.stringify(newfileList));
  } else {
    fileList.value = [];
  }
  emit("update:modelValue", JSON.stringify(newfileList));
}
// 超出上传数限制
function handleExceed(files, uploadFiles) {
  $ekMessage.warning('超出文件上传数限制');
}
// 文件上传成功时的钩
function handleSuccess(response, uploadFile, uploadFiles) {
  emit("on-success", response, uploadFile, uploadFiles);
  let newfileList = getFileList(JSON.parse(JSON.stringify(uploadFiles)));
  fileList.value = JSON.parse(JSON.stringify(newfileList));
  emit("update:modelValue", JSON.stringify(newfileList));
}
// 文件上传失败时的钩子
function handleError(error, uploadFile, uploadFiles) {
  // emit("on-error", error, uploadFile, uploadFiles);
  $ekMessage.error(error.message);
}
// 文件上传时的钩子
function handleProgress(event, uploadFile, uploadFiles) {
  // console.log(event,'event')
  // emit("on-progress", event, uploadFile, uploadFiles);
}
// 文件上传的钩子
function handleChange(uploadFile, uploadFiles) {
  // console.log(uploadFiles,'uploadFiles')
}
const ekUpload = ref(null);
function submit() {
  ekUpload.value.submit();
}
defineExpose({
  submit
});

// todo 多文件上传时候如何判断全部上传完毕，每次成功都赋值重新修改值是否正确？文件下载功能
</script>

<style scoped lang="scss">
.ek-upload-file {
    width: 220px;
  .ek-upload-file-box {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .ek-upload-file-btn {
    }
    :deep(.el-upload-list) {
      width: 220px;
    }
  }
}
</style>
